import dynamic from 'next/dynamic'
import Responsive from '@c/responsive'
import LiveItem from '@c/live/live-item'
import Footer from '@c/footer'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import {   getLiveCollectList } from '@/api/history-collect'
import {  getImportSource } from '@/api/selfbuild'
import { getChannels } from '@/api/live'
import { useShowLogin, useScrollSessionStore } from '@/utils/hooks'
import cm from 'classnames'

const GuideDownload = dynamic(() => import('@c/guide-download'))
const SelfDetail = dynamic(() => import('@c/live/self-detail'))
const SelfItem = dynamic(() => import('@c/live/self-item'))

const Index = props => {
  const pageScroll = 'liveScroll'
  useScrollSessionStore(pageScroll)
  const { list } = props
  const [selfList, setSelfList] = useState(null)
  const [isLive, setIsLive] = useState('live')
  const [selectedLive, setSelectedLive] = useState([])
  const [isSelfDetail, setIsSelfDetail] = useState(false)
  const setShowLogin = useShowLogin()
  // 获取已收藏的频道
  const getSelectedChannels = async token => {
    const res = await getLiveCollectList({ pageNo: 1, pageSize: 9999 }, token)
    setSelectedLive(res?.data?.list || [])
  }
  // 加载用户数据
  useEffect(() => {
    const token = localStorage.getItem('token')
    if (token) {
      getSelectedChannels(token)
    }
    const top = sessionStorage.getItem(pageScroll) || 0
    window.scroll(0, top)
    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [])

  const toLive = () => setIsLive('live')
  //切换自建频道时，获取数据。
  const fetchSelfData = async (token, type) => {
    if (selfList && type !== 'update') {
      return
    }
    const res = await getImportSource(token)
    const validSource = (res.data?.sources || []).filter(item => {
      if (!item.source?.length) {
        return false
      }
      return !item.source.every(child => !child.alive)
    })
    setSelfList(validSource)
  }
  const toSelf = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      setShowLogin(true)
      return
    }
    fetchSelfData(token)
    setIsLive('self')
  }

  if (isSelfDetail) {
    return (
      <Responsive top={100}>
        <SelfDetail
          onBack={() => setIsSelfDetail(false)}
          updateList={() => fetchSelfData(localStorage.getItem('token'), 'update')}
        />
        <Footer top={20} />
      </Responsive>
    )
  }

  return (
    <Responsive top={100}>
      {selectedLive.length ? <LiveItem data={selectedLive} name="已收藏" top={0} bottom={28} /> : null}
      <div className={cm(styles.liveTab, styles.liveTabPhone)}>
        <h1 onClick={toLive} className={isLive === 'live' ? styles.active : ''}>
          电视直播
        </h1>
        <span onClick={toSelf} className={isLive === 'self' ? styles.active : ''}>
          自建频道
        </span>
      </div>
      {isLive === 'live' ? (
        <>
          <GuideDownload top={40} bottom={40} />
          {list.map((item, index) => {
            return <LiveItem data={item.value || []} top={28} key={index} name={item.key} />
          })}
        </>
      ) : null}
      {isLive === 'self' ? (
        <SelfItem
          data={selfList}
          top={28}
          updateList={() => fetchSelfData(localStorage.getItem('token'), 'update')}
          toDetail={() => setIsSelfDetail(true)}
        />
      ) : null}
      <Footer />
    </Responsive>
  )
}
export default Index

const formatData = data => {
  const list =
    data?.reduce((target, curr) => {
      target.push({
        key: curr.name,
        value: curr.channels
      })
      return target
    }, []) || []
  return list
}

export async function getServerSideProps() {
  const res = await getChannels({})
  const list = formatData(res?.data?.channelGroups || [])
  return {
    props: {
      list,
      layoutProps: {
        noSomeMetaInfo: false,
        url: '/live',
        title: '电视直播线上看，大陆港台新马频道大全 - 星视界',
        desc: '星视界专为海外华人定制的电视直播，免费无广告；内容涵盖大陆央视卫视，港台电视直播以及新马等地的300+电视台，全球加速，稳定播放。更提供电视版App免费下载，体验完整大屏直播体验。'
      }
    }
  }
}
